package com.baton.plugins.finder;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

/**
 * Servlet implementation class delServlet
 */
@WebServlet("/delFinder.java")
public class DelServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DelServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		getResponse(request, response);
	}


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

	private void getResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = response.getWriter();
		Map<String,Object> map = new HashMap<String,Object>();
		String command = request.getParameter("command");
		String basePath = getServletContext().getRealPath("/userfiles/grandid/userid");
		String id = request.getParameter("id");
		id = URLDecoder.decode(id, "UTF-8").replaceAll("\\\\", "/");
		String pid = request.getParameter("pid");
		pid = URLDecoder.decode(pid, "UTF-8").replaceAll("\\\\", "/");
		if("getFiles".equals(command)){
			String path = getServletContext().getRealPath("/userfiles/grandid/userid" + "/" + id);
			File file = new File(path);
			if(!file.isDirectory()){
				file.delete();
				map.put("success", true);
				map.put("msg", "文件删除成功");
			}else if(removeFile(file)){
				map.put("success", true);
				map.put("msg", "目录删除成功");
			}else {
				map.put("success", false);
				map.put("msg", "删除失败");
			}
		}
		out.println(JSON.toJSONString(map));

	}
	
	private boolean removeFile(File file){
		File[] files = file.listFiles();
		for(File r:files){
			if(r.isDirectory()){
				removeFile(r);
			} else {
				r.delete();
			}
		}
		boolean del = file.delete();
		if(del){
			return true;
		}else {
			return false;
		}
	
	}
}
